<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:lkUser:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:lkUser:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:lkUser:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['base:lkUser:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lkUserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="性别" :formatter="sexFormat" align="center" prop="sex" />
      <el-table-column label="电话" align="center" prop="phonenumber" />
<!--      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="驾驶员姓名" align="center" prop="lkUser.nickName" />
      <el-table-column label="驾驶员性别" :formatter="driverSexFormat" align="center" prop="lkUser.sex" />
      <el-table-column label="驾驶员电话" align="center" prop="lkUser.phonenumber" />
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定车辆数" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          {{scope.row.equipmentCount}}
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleBindVehicle(scope.row)"
            v-hasPermi="['base:lkUser:edit']"
          >去绑定</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="equipment" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名:" >
              <b>{{form.nickName}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号:" >
              <b>{{form.phonenumber}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址:" >
              <b>{{form.address}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备编号:"  prop="equipmentNumber">
              <el-input @input="handlerQueryEquipment" v-model="equipmentNumber" placeholder="设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="IMEI号:" >
              <b style="">{{equipment==undefined?'':equipment.imei}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号:" >
              <b style="">{{equipment==undefined?'':equipment.equipmentModel}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物联网卡号:" >
              <b style="">{{equipment==undefined?'':equipment.cardNumber}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆型号:" >
              <b style="">{{equipment==undefined?'':equipment.vehicleModel}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车身颜色:" >
              <b style="">{{equipment==undefined?'':equipment.vehicleColor}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电机号:" >
              <b style="">{{equipment==undefined?'':equipment.motorNumber}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架号:" >
              <b style="">{{equipment==undefined?'':equipment.frameNumber}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电池类型:" prop="batteryType" >
              <el-select v-model="equipment.batteryType"  placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in batteryTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电池电压:" prop="batteryVoltage">
              <el-select v-model="equipment.batteryVoltage"  placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dict in batteryVoltageOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLkUser, getLkUser, delLkUser, addLkUser, updateLkUser, exportLkUser } from "@/api/base/lkUser";
import {getEquipmentByNumber, updateEquipment} from "@/api/base/equipment";

export default {
  name: "LkUser",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      lkUserList: [],
      // 性别状态字典
      sexOptions: [],
      // 日期范围
      dateRange: [],
      batteryTypeOptions:[],
      batteryVoltageOptions:[],
      // 弹出层标题
      title: "",
      equipmentNumber:"",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phonenumber: null,
        password: null,
        nickName: null,
        sex: null,
        birthday: null,
        address: null,
        deviceNumber: null,
        avatar: null,
        parentId: null,
        createTime: null,
        delStatus: null
      },
      // 表单参数
      form: {},
      equipment:{},
      // 表单校验
      rules: {
        equipmentNumber: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        batteryType: [
          { required: true, message: "请选择电池类型", trigger: "select" }
        ],
        batteryVoltage: [
          { required: true, message: "请选择电池电压", trigger: "select" }
        ]

      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
  },
  methods: {
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      listLkUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.lkUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    driverSexFormat(row, column) {
      if(row.lkUser!=null){
        return this.selectDictLabel(this.sexOptions, row.lkUser.sex);
      }
      return "";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        phonenumber: null,
        password: null,
        nickName: null,
        sex: null,
        birthday: null,
        address: null,
        deviceNumber: null,
        avatar: null,
        parentId: null,
        createTime: null,
        delStatus: 0
      };
      this.resetForm("form");
      this.equipment={};
      this.equipmentNumber="";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    handlerQueryEquipment(value){
      this.equipment={}
      if (value!=''){
        getEquipmentByNumber(value).then(response => {
          if(response.data!=undefined){
            this.equipment = response.data;
          }
        });
      }
    },
    /** 绑定车辆操作 */
    handleBindVehicle(row) {
      this.reset();
      this.getDicts("battery_type").then(response => {
        this.batteryTypeOptions = response.data;
      });
      this.getDicts("battery_voltage").then(response => {
        this.batteryVoltageOptions = response.data;
      });
      const userId = row.userId || this.ids
      getLkUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "绑定车辆";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            if(this.equipment.id==undefined){
              this.msgError("未找到改设备")
              return;
            }
            if(this.equipment.userId!=null){
              this.msgError("该设备已经被绑定")
              return;
            }
            this.equipment.userId=this.form.userId;
            this.equipment.activateStatus="0";
            this.equipment.activateTime=new Date();
            updateEquipment(this.equipment).then(response => {
              this.msgSuccess("绑定成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除用户信息编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLkUser(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportLkUser(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    }
  }
};
</script>
